/**
 * Created by liyun. 商家打款给用户
 */

var fs = require('fs');
var xml2js = require('xml2js');
var md5 = require('MD5');
var _ = require("underscore");
var debug = require('debug')('lifewx:Epayment');
var https = require('https');
var url_mod = require('url');
var url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';

var Epayment = function (partnerKey) {
    this.partnerKey = partnerKey;

    if (typeof this.paymentToUser != 'function') {
        Epayment.prototype.paymentToUser = function (params, callback) {

            params = _.extend(params,{
                "sign": this.getSign(params)
            });

            //使用https的post的请求
            var parsed_url = url_mod.parse(url);
            var options = {
                host: parsed_url.host,
                port: 443,
                path: parsed_url.path,
                pfx: fs.readFileSync(__dirname + '/cert/apiclient_cert.p12'),
                passphrase: params.mchid,
                method: 'POST'
            };
            var req = https.request(options, function(res) {
                var content = '';
                res.on('data', function(chunk) {
                    content += chunk;
                });
                res.on('end', function(){
                    debug('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~');
                    debug(content);
                    debug('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~');
                    xml2js.parseString(content, {//转换json
                        trim: true,
                        explicitArray: false
                    }, function (err, json) {
                        var error = null,
                            data;
                        if (err) {
                            error = new Error();
                            err.name = "XMLParseError";
                            return callback(err, xml);
                        }

                        data = json ? json.xml : {};
                        // debug('~~~~~~~~~~~~~~~~~~~~~~~~~~~~');
                        // debug(data);
                        // debug('~~~~~~~~~~~~~~~~~~~~~~~~~~~~');
                        callback(null, data);
                    });
                });
            });

            req.on('error', function(e) {
                callback(e);
            });
            req.write(this.buildXml(params));
            req.end();
        }
    }
    if (typeof this.buildXml != 'function') {
        Epayment.prototype.buildXml = function (obj) {
            var builder = new xml2js.Builder();
            var xml = builder.buildObject({xml: obj});
            debug(xml);
            return xml;
        };
    }
    if (typeof this.getSign != 'function') {
        Epayment.prototype.getSign = function (pkg) {
            var string1 = this.toQueryString(pkg);
            var stringSignTemp = string1 + "&key=" + this.partnerKey;
            var signValue = md5(stringSignTemp).toUpperCase();
            debug(signValue);
            return signValue;
        };
    }
    if (typeof this.toQueryString != 'function') {
        Epayment.prototype.toQueryString = function (object) {
            return Object.keys(object).filter(function (key) {
                return object[key] !== undefined && object[key] !== '';
            }).sort().map(function (key) {
                return key + "=" + object[key];
            }).join("&");
        };
    }
    if (typeof this.generateTimeStamp != 'function') {
        Epayment.prototype.generateTimeStamp = function () {
            return parseInt(+new Date() / 1000, 10) + ""
        };
    }
    if (typeof this.generateNonceStr != 'function') {
        Epayment.prototype.generateNonceStr = function (length) {
            var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            var maxPos = chars.length;
            var noceStr = "";
            var i;
            for (i = 0; i < (length || 32); i++) {
                noceStr += chars.charAt(Math.floor(Math.random() * maxPos));
            }
            return noceStr;
        };
    }


};
module.exports = Epayment;